﻿(function($) {

    var ACTIVATED_CLASS = "panel-header-image-activated";

    var BUTTONS = {
        minimize : {
            id: "collapsed",
            url: "images/panel/minimize.png",
            activated: false,
            title: i18n.panel.collapse,
            alt: "_"
        },
        restore : {
            id: "restored",
            url: "images/panel/restore-down.png",
            activated: true,
            title: i18n.panel.restore,
            alt: "*"
        },
        maximize : {
            id: "expanded",
            url: "images/panel/maximize.png",
            activated: false,
            title: i18n.panel.expand,
            alt: "#"
        }
    };

    $.fn.extend({
        collapsiblePanel: function(buttonHandlers) {
            function createImage(handler, button) {
                var settings = BUTTONS[button];

                var $img = $("<img src='" + settings.url + "' alt='" + settings.alt + "' title='" + settings.title +
                        "' class='panel-header-image " + settings.id + "' class-id='" + settings.id + "'/>").click(function() {
                            var $this = $(this);
                            var $parent = $this.parent();
                            var $header = $parent.parent();
                            var $activated = $parent.children("[class*='" + ACTIVATED_CLASS + "']");

                            $activated.removeClass(ACTIVATED_CLASS);
                            $this.addClass(ACTIVATED_CLASS);

                            var panelId = $header.children(":first").attr("for");

                            var $panel = panelId ? $("#" + panelId) : $header.next();

                            var newClass = $this.attr("class-id");
                            var oldClass = $activated.attr("class-id");

                            $header.removeClass(oldClass).addClass(newClass);
                            $panel.removeClass(oldClass).addClass(newClass);


                            handler.call($panel[0], $header[0]);
                        });

                if (settings.activated) {
                    $img.addClass(ACTIVATED_CLASS);
                }

                return $img;
            }

            return $(this).each(function() {
                var $this = $(this);
                var $header = $("<div class='panel-header ui-widget-header'></div>");
                var $images = $("<div class='panel-header-images'></div>");

                $this.replaceWith($header);

                $header.append($this);

                $images.append.apply($images, $.map(buttonHandlers, createImage));

                $header.append($images);
            });
        }
    });
})(jQuery);